import { defineStore } from "pinia"
import { ref } from "vue"
import { createProblem as apiCreateProblem, deleteProblem as apiDeleteProblem, getProblemDetail, getProblemList as apiGetProblemList, updateProblem as apiUpdateProblem } from "@/api/modules/problem"

export const useProblemsStore = defineStore("problem", () => {
  const problems = ref([])
  const loading = ref(false)
  const total = ref(0)
  const currentProblem = ref(null)

  async function getProblemList(params = {}) {
    loading.value = true
    try {
      const response = await apiGetProblemList(params)

      if (response && response.code === 200 && response.data) {
        const data = response.data
        problems.value = Array.isArray(data.records) ? data.records : []
        total.value = data.total === 0 && problems.value.length > 0 ? problems.value.length : typeof data.total === "number" ? data.total : 0
        return response
      } else {
        problems.value = []
        total.value = 0
        throw new Error(response?.message || "获取题目列表失败")
      }
    } finally {
      loading.value = false
    }
  }

  async function getProblemById(id) {
    loading.value = true
    try {
      const response = await getProblemDetail(id)

      if (response && response.code === 200 && response.data) {
        currentProblem.value = response.data
        return response
      } else {
        throw new Error(response?.message || "获取题目详情失败")
      }
    } finally {
      loading.value = false
    }
  }

  async function createProblem(problemData) {
    loading.value = true
    try {
      const formattedData = {
        title: problemData.title,
        description: problemData.description,
        difficulty: problemData.difficulty,
        category: problemData.category || "算法",
        inputDescription: problemData.inputDescription || "",
        outputDescription: problemData.outputDescription || "",
        sampleInput: problemData.sampleInput,
        sampleOutput: problemData.sampleOutput,
        hint: problemData.hint || "",
        timeLimit: problemData.timeLimit || 1000,
        memoryLimit: problemData.memoryLimit || 256,
        totalScore: problemData.totalScore || 100,
        status: problemData.status || "草稿",
        isPublic: problemData.isPublic !== undefined ? problemData.isPublic : true
      }

      return await apiCreateProblem(formattedData)
    } finally {
      loading.value = false
    }
  }

  async function updateProblem(id, problemData) {
    loading.value = true
    try {
      const formattedData = {
        title: problemData.title,
        description: problemData.description,
        difficulty: problemData.difficulty,
        category: problemData.category,
        inputDescription: problemData.inputDescription,
        outputDescription: problemData.outputDescription,
        sampleInput: problemData.sampleInput,
        sampleOutput: problemData.sampleOutput,
        hint: problemData.hint,
        timeLimit: problemData.timeLimit,
        memoryLimit: problemData.memoryLimit,
        totalScore: problemData.totalScore,
        status: problemData.status,
        isPublic: problemData.isPublic
      }

      const response = await apiUpdateProblem(id, formattedData)

      if (response && response.code === 200) {
        const updatedData = response.data || response
        const index = problems.value.findIndex(problem => problem.id === id)
        if (index !== -1 && updatedData) {
          problems.value[index] = { ...problems.value[index], ...updatedData }
        }
        return { code: 200, data: updatedData, message: response.message || "更新成功" }
      }
      return response
    } finally {
      loading.value = false
    }
  }

  async function deleteProblem(id) {
    loading.value = true
    try {
      const result = await apiDeleteProblem(id)

      if (result && result.code === 200) {
        const index = problems.value.findIndex(problem => problem.id === id)
        if (index !== -1) {
          problems.value.splice(index, 1)
          total.value = Math.max(0, total.value - 1)
        }
        return result
      } else {
        throw new Error(result?.message || "题目删除失败")
      }
    } finally {
      loading.value = false
    }
  }

  function clearProblems() {
    problems.value = []
    total.value = 0
  }

  function resetLoading() {
    loading.value = false
  }

  function resetCurrentProblem() {
    currentProblem.value = null
  }

  return {
    problems,
    loading,
    total,
    currentProblem,
    getProblemList,
    getProblemById,
    createProblem,
    updateProblem,
    deleteProblem,
    clearProblems,
    resetLoading,
    resetCurrentProblem
  }
})
